const express = require('express');
const router = express.Router();
const {query} = require('../models/db');
const {Live} = require('../models');

/* 设置子路由. */
router.get('/', async (req, res, next) => {

    try {

        const page = +req.query.page || 1;//获取当前页码，没有默认1
        const size = +req.query.size || 5;//每页条数
        const offset = (page - 1) * size;
        const livesql = 'SELECT * FROM kaikeba.live ORDER BY bTime DESC LIMIT ?,?';
        const results = await query(livesql, [offset, size]);

        for (const result of results) {
            const now = new Date();
            const livetime = new Date(result.lTime);
            const beginTime = new Date(result.bTime);
            if (beginTime - now >= 0) {
                result.isYuyue = true;
            } else if (livetime - now <= 0) {
                result.isEnd = true;
            } else {
                result.isLive = true;
            }
        }
 
        const count = await query('SELECT count(*) as count FROM kaikeba.live ').then(results => results[0].count);
        res.render('page/live', {
            title: '芒果直播',
            tolive: results,
            pagination: getPagination(count, page, size),
        });
//,
    } catch (err) {
        console.log(err);
        next(err);
    }

});

router.get('/bySeq', async (req, res, next) => {
    try {
        const page = +req.query.page || 1;//获取当前页码，没有默认1
        const size = +req.query.size || 5;//每页条数

        //返回带总条数带对象 {rows:[],count}
        const results = await Live.findAndCountAll({
            offset: (page - 1) * size,//分页偏移量
            limit: size,//查询条数
            order: [['time', 'DESC']]//排序，可多选条件
        });
        res.render('page/live', {
            tolive: results.rows,
            pagination: getPagination(results.count, page, size),
        });
    } catch (err) {
        console.log(err);
        next(err);
    }
});

function getPagination(count, page, size) {
    const total = Math.ceil(count / size);//总页数
    const first = page !== 1;
    const last = page !== total;
    const prev = page > 1;
    const next = page < total;
    return {page, total, first, last, prev, next}
}

module.exports = router;
